import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, Modal, message as msg} from 'antd';
import {
    FORM_OPTIONS, DATETIME_FORMAT,
    TABLE,
    PAGINATION_OPTIONS,
    PAGE,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT
} from '../constants';
import {formatDateTime, formatAmount, conventEnumValueToString} from '../utils';
import TextInput from 'Shared/components/TextInput';
import SelectAlert from '../common/SelectAlert';
import {conventSorter, computeSelectedRows} from './utils';
import styles from './style.css';
import {getClaim, getClaimSimple} from './api';
import {injectIntl} from './intl';
import {claimStatus, claimSettlementStatus, usedPartStatus, repairType} from '../Enum';
import DateRangePicker from 'Shared/components/DateRangePicker';
import moment from 'moment';
const MultiSelectAlert = SelectAlert.Multi;
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
class ClaimApply extends PureComponent {
    state = {
        loading: false,
        keys: [],
        rows: [],
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        vin: '',
        code: '',
        causePartName: '',
        causePartCode: '',
        submitTime: [],
        approveTime: [],
        createTime: [],
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    onSearchSimple = code => getClaimSimple({
        code,
        status: [claimStatus.审核通过],
        settlementStatus: claimSettlementStatus.已结算,
        dealerId: this.props.dealerId,
        brandId: this.props.brandId,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
    })
    onQuery = condition => {
        const {createTime, ...props} = condition;
        if(createTime && createTime.length) {
            props.beginCreateTime = moment(createTime[0]).toISOString();
            props.endCreateTime = moment(createTime[1]).toISOString();
        }
        this.setState({isFetching: true});
        getClaim({
            status: [claimStatus.审核通过],
            dealerId: this.props.dealerId,
            brandId: this.props.brandId,
            settlementStatus: claimSettlementStatus.已结算,
            ...props,
        })
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: EMPTY_OBJECT,
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            vin: this.state.vin,
            code: this.state.code,
            causePartName: this.state.causePartName,
            causePartCode: this.state.causePartCode,
            submitTime: this.state.submitTime,
            approveTime: this.state.approveTime,
            createTime: this.state.createTime,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }
    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: EMPTY_ARRAY,
            rows: EMPTY_ARRAY
        });
    }
    onSubmit = () => {
        if(!this.state.rows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'claimApply.validate.order',
                defaultMessage: '请选择维修索赔单'
            }));
        this.props.onSelect(this.state.rows);
    }
    onClickReset = () => {
        this.setState({
            currentCondition: {},
            vin: '',
            code: '',
            causePartName: '',
            causePartCode: '',
            submitTime: [],
            approveTime: [],
            createTime: [],
        });
    }
    render() {
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.code',
                    defaultMessage: '索赔单号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.brandCode',
                    defaultMessage: '品牌'
                }),
                sorter: true,
                dataIndex: 'brandCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.causePartCode',
                    defaultMessage: '主损件编号'
                }),
                dataIndex: 'causePartCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.causePartName',
                    defaultMessage: '主损件名称'
                }),
                dataIndex: 'causePartName'
            },
            {
                title: 'VIN',
                dataIndex: 'vin',
                sorter: true
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode',
                sorter: true
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                render: text => conventEnumValueToString(claimStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.settlementStatus',
                    defaultMessage: '结算状态'
                }),
                dataIndex: 'settlementStatus',
                sorter: true,
                render: text => conventEnumValueToString(claimSettlementStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.usedPartStatus',
                    defaultMessage: '旧件状态'
                }),
                dataIndex: 'usedPartStatus',
                sorter: true,
                render: text => conventEnumValueToString(usedPartStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.repairType',
                    defaultMessage: '索赔类型'
                }),
                dataIndex: 'repairType',
                sorter: true,
                render: text => conventEnumValueToString(repairType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.totalFee',
                    defaultMessage: '费用合计'
                }),
                dataIndex: 'totalFee',
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.submitTime',
                    defaultMessage: '提交时间'
                }),
                dataIndex: 'submitTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'claimApply.approveTime',
                    defaultMessage: '审核时间'
                }),
                dataIndex: 'approveTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            keys: this.state.keys,
            onChange: (keys, rows) => {
                const selectedRows = computeSelectedRows(this.state.keys, this.state.rows, keys, rows);
                this.setState({
                    keys,
                    rows: selectedRows
                });
            },
            getCheckboxProps: record => ({
                disabled: this.props.currentSelectRowkeys.some(v => v.sourceId === record.id)
            })
        };
        return (
            <div>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'claimApply.claim.title',
                        defaultMessage: '维修索赔单查询'
                    })}
                    width="60%"
                    maskClosable={false}
                    footer={null}
                    destroyOnClose={true}
                    visible={true}
                    onCancel={this.props.onCancel}>
                    <Form className="form-standard">
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'claimApply.code',
                                        defaultMessage: '索赔单号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="code"
                                        value={this.state.code}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'claimApply.causePartCode',
                                        defaultMessage: '主损件编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="causePartCode"
                                        value={this.state.causePartCode}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'claimApply.causePartName',
                                        defaultMessage: '主损件名称'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="causePartName"
                                        value={this.state.causePartName}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label="VIN" {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="vin"
                                        value={this.state.vin}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'claimApply.createTime',
                                        defaultMessage: '创建时间'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DateRangePicker
                                        name="createTime"
                                        value={this.state.createTime}
                                        onChange={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'claimApply.submitTime',
                                        defaultMessage: '提交时间'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DateRangePicker
                                        name="submitTime"
                                        value={this.state.submitTime}
                                        onChange={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'claimApply.approveTime',
                                        defaultMessage: '审核时间'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DateRangePicker
                                        name="approveTime"
                                        value={this.state.approveTime}
                                        onChange={this.onChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                <Button type="primary" onClick={this.onClickSearchBtn}>
                                    {this.props.intl.formatMessage({
                                        id: 'claimApply.btn.search',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                                <Button key="clear" onClick={this.props.onClickReset}>
                                    {this.props.intl.formatMessage({
                                        id: 'claimApply.btn.reset',
                                        defaultMessage: '重置'
                                    })}
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                    <Divider className={styles.divider} />
                    <MultiSelectAlert data={this.state.rows}
                        onConfirm={this.onSubmit}
                        onDelete={this.onCloseTag}
                        onDeleteAll={this.onCloseTag}/>
                    <Table
                        className={`white-space-nowrap ${styles.tableCursor}`}
                        rowKey="id"
                        dataSource={this.state.data.content || EMPTY_ARRAY}
                        columns={columns}
                        loading={isFetching || this.state.loading}
                        pagination={pagination}
                        onChange={this.handleTableChange}
                        rowSelection={rowSelection}
                        {...TABLE}
                        locale={{
                            emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                        }} />
                </Modal>
            </div >
        );
    }
}

ClaimApply.propTypes = {
    onSelect: PropTypes.func.isRequired,
    brandId: PropTypes.string,
    currentSelectRowkeys: PropTypes.array,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    value: PropTypes.object,
    onCancel: PropTypes.func,
};

export default injectIntl(ClaimApply);
